package tcos

import (
	"fmt"
	"context"
    //"strings"
	"net/url"
    "net/http"
	"io/ioutil"
    "github.com/tencentyun/cos-go-sdk-v5"
)

func UploadObj(appId,region,secretId,secretKey,cosPath,localPath,cosReturnUrl string)(string, error) {
	addr := "https://" + appId + ".cos." + region + ".myqcloud.com"
    u, _ := url.Parse(addr)
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID: secretId,
            SecretKey: secretKey,  
        },
    })
    _, err := c.Object.PutFromFile(context.Background(),cosPath,localPath, nil)
    if err != nil {
        return "", err
    }
	path := cosReturnUrl + "/" + cosPath
	return path, nil
}

func DeleteObj(appId,region,secretId,secretKey,cosPath string) error {
    addr := "https://" + appId + ".cos." + region + ".myqcloud.com"
    u, _ := url.Parse(addr)
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID: secretId,
            SecretKey: secretKey,  
        },
    })
    _, err := c.Object.Delete(context.Background(), cosPath)
    if err != nil {
       return err
    }
	return nil
}

func DownloadObj(appId,region,secretId,secretKey string) {
    addr := "https://" + appId + ".cos." + region + ".myqcloud.com"
    u, _ := url.Parse(addr)
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID: secretId,
            SecretKey: secretKey,  
        },
    })
    // 1.Get object content by resp body.
    cosPath := "test/hello.txt"
    resp, err := c.Object.Get(context.Background(), cosPath, nil)
    if err != nil {
        panic(err)
    }
    bs, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    fmt.Printf("%s\n", string(bs))
    // 2.Get object to local file path.
    _, err = c.Object.GetToFile(context.Background(), cosPath, "example", nil)
    if err != nil {
        panic(err)
    }
}

func QueryObj(appId,region,secretId,secretKey string) {
	addr := "https://" + appId + ".cos." + region + ".myqcloud.com"
    u, _ := url.Parse(addr)
    b := &cos.BaseURL{BucketURL: u}
    c := cos.NewClient(b, &http.Client{
        Transport: &cos.AuthorizationTransport{
            SecretID: secretId,
            SecretKey: secretKey,  
        },
    })
    opt := &cos.BucketGetOptions{
        Prefix:  "test",
        MaxKeys: 3,
    }
    v, _, err := c.Bucket.Get(context.Background(), opt)
    if err != nil {
        panic(err)
    }
    for _, c := range v.Contents {
        fmt.Printf("%s, %d\n", c.Key, c.Size)
    }
}
